/**
 * 设置组件 - 用于显示和编辑配置
 */

// 初始化设置面板
function initSettings() {
    createSettingsButton();
    createSettingsPanel();
    createOverlay();
    
    // 监听配置变化
    if (window.ConfigManager) {
        window.ConfigManager.addEventListener('configChanged', (config) => {
            updateSettingsForm(config);
        });
    }
    
    // 监听API预设选择变化
    setupApiPresetListener();
}

// 设置API预设监听
function setupApiPresetListener() {
    document.addEventListener('change', function(e) {
        if (e.target && e.target.id === 'api-preset') {
            const preset = e.target.value;
            const form = document.getElementById('settings-panel');
            if (!form) return;
            
            const apiUrlInput = form.querySelector('#api-url');
            const modelSelect = form.querySelector('#model');
            
            switch (preset) {
                case 'openai':
                    apiUrlInput.value = 'https://api.openai.com/v1/chat/completions';
                    if (modelSelect.querySelector('option[value="gpt-3.5-turbo"]')) {
                        modelSelect.value = 'gpt-3.5-turbo';
                    }
                    break;
                case 'dashscope':
                    apiUrlInput.value = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
                    if (modelSelect.querySelector('option[value="qwen"]')) {
                        modelSelect.value = 'qwen';
                    }
                    break;
                case 'dashscope-qwq':
                    apiUrlInput.value = 'https://dashscope.aliyuncs.com/compatible-mode/v1';
                    if (modelSelect.querySelector('option[value="qwq-32b"]')) {
                        modelSelect.value = 'qwq-32b';
                    }
                    break;
                // 自定义选项不做任何更改
            }
        }
    });
}

// 创建设置按钮
function createSettingsButton() {
    const button = document.createElement('button');
    button.className = 'settings-button';
    button.innerHTML = '⚙️';
    button.title = 'AI配置设置';
    
    button.addEventListener('click', toggleSettingsPanel);
    
    // 添加到页面左下角
    const container = document.createElement('div');
    container.className = 'settings-button-container';
    container.appendChild(button);
    
    document.body.appendChild(container);
}

// 创建遮罩层
function createOverlay() {
    const overlay = document.createElement('div');
    overlay.className = 'settings-overlay';
    overlay.id = 'settings-overlay';
    
    overlay.addEventListener('click', closeSettingsPanel);
    
    document.body.appendChild(overlay);
}

// 创建设置面板
function createSettingsPanel() {
    const panel = document.createElement('div');
    panel.className = 'settings-panel';
    panel.id = 'settings-panel';
    
    panel.innerHTML = `
        <div class="settings-header">
            <h2>AI配置设置</h2>
            <button class="settings-close-btn">&times;</button>
        </div>
        <div class="settings-content">
            <div class="settings-group">
                <label for="api-preset">API预设</label>
                <select id="api-preset" class="settings-input">
                    <option value="custom">自定义</option>
                    <option value="openai">OpenAI</option>
                    <option value="dashscope">阿里云通义千问</option>
                    <option value="dashscope-qwq">阿里云QWQ-32B(含思考过程)</option>
                </select>
            </div>
            <div class="settings-group">
                <label for="api-key">API密钥</label>
                <input type="password" id="api-key" class="settings-input" placeholder="输入您的API密钥">
            </div>
            <div class="settings-group">
                <label for="api-url">API URL</label>
                <input type="text" id="api-url" class="settings-input" placeholder="API服务地址">
            </div>
            <div class="settings-group">
                <label for="model">默认模型</label>
                <select id="model" class="settings-input">
                    <option value="qwen">通义千问</option>
                    <option value="qwq-32b">QWQ-32B(思考+回答)</option>
                    <option value="deepseek">Deepseek</option>
                    <option value="r1-qwen-32">R1-Qwen-32B</option>
                    <option value="r1-llama-70">R1-Llama-70B</option>
                    <option value="gpt-3.5-turbo">GPT-3.5-Turbo</option>
                    <option value="gpt-4o">GPT-4o</option>
                </select>
            </div>
            <div class="settings-actions">
                <button class="settings-save-btn">保存</button>
                <button class="settings-reset-btn">重置</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(panel);
    
    // 添加事件监听器
    panel.querySelector('.settings-close-btn').addEventListener('click', closeSettingsPanel);
    panel.querySelector('.settings-save-btn').addEventListener('click', saveSettings);
    panel.querySelector('.settings-reset-btn').addEventListener('click', resetSettings);
    
    // 初始化表单
    if (window.ConfigManager) {
        updateSettingsForm(window.ConfigManager.getConfig());
    }
}

// 切换设置面板显示状态
function toggleSettingsPanel() {
    const panel = document.getElementById('settings-panel');
    const overlay = document.getElementById('settings-overlay');
    
    if (panel) {
        panel.classList.toggle('active');
        
        if (overlay) {
            overlay.classList.toggle('active');
        }
    }
}

// 关闭设置面板
function closeSettingsPanel() {
    const panel = document.getElementById('settings-panel');
    const overlay = document.getElementById('settings-overlay');
    
    if (panel) {
        panel.classList.remove('active');
    }
    
    if (overlay) {
        overlay.classList.remove('active');
    }
}

// 保存设置
function saveSettings() {
    const form = document.getElementById('settings-panel');
    if (!form) return;
    
    const config = {
        apiPreset: form.querySelector('#api-preset').value,
        apiKey: form.querySelector('#api-key').value,
        baseUrl: form.querySelector('#api-url').value,
        model: form.querySelector('#model').value
    };
    
    if (window.ConfigManager) {
        window.ConfigManager.saveConfig(config);
    }
    
    // 显示保存成功的提示
    showSaveSuccess();
    
    // 关闭设置面板
    closeSettingsPanel();
}

// 显示保存成功提示
function showSaveSuccess() {
    // 创建一个成功通知
    const notification = document.createElement('div');
    notification.className = 'settings-notification success';
    notification.innerHTML = `
        <div class="notification-icon">✓</div>
        <div class="notification-content">
            <div class="notification-title">保存成功</div>
            <div class="notification-message">您的AI设置已成功保存</div>
        </div>
    `;
    
    // 添加到body
    document.body.appendChild(notification);
    
    // 设置样式
    Object.assign(notification.style, {
        position: 'fixed',
        bottom: '20px',
        right: '20px',
        zIndex: 9999,
        backgroundColor: 'rgba(240, 255, 240, 0.95)',
        borderRadius: '8px',
        boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
        border: '1px solid rgba(0, 200, 0, 0.2)',
        padding: '12px 15px',
        display: 'flex',
        alignItems: 'center',
        fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        maxWidth: '300px',
        animation: 'settingsNotificationIn 0.3s forwards'
    });
    
    // 创建动画
    const style = document.createElement('style');
    style.innerHTML = `
        @keyframes settingsNotificationIn {
            from { transform: translateY(100%); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        @keyframes settingsNotificationOut {
            from { transform: translateY(0); opacity: 1; }
            to { transform: translateY(100%); opacity: 0; }
        }
        .notification-icon {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            background-color: #34C759;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            flex-shrink: 0;
        }
        .notification-content {
            flex: 1;
        }
        .notification-title {
            font-weight: bold;
            margin-bottom: 4px;
        }
        .notification-message {
            font-size: 14px;
            color: #555;
        }
    `;
    document.head.appendChild(style);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (document.body.contains(notification)) {
            notification.style.animation = 'settingsNotificationOut 0.3s forwards';
            setTimeout(() => {
                if (document.body.contains(notification)) {
                    document.body.removeChild(notification);
                }
            }, 300);
        }
    }, 3000);
}

// 重置设置
function resetSettings() {
    if (window.ConfigManager) {
        if (confirm('确定要重置所有设置吗？')) {
            window.ConfigManager.resetConfig();
            showSettingsToast('配置已重置');
            closeSettingsPanel();
        }
    }
}

// 更新设置表单
function updateSettingsForm(config) {
    const form = document.getElementById('settings-form');
    if (!form) return;
    
    form.querySelector('#api-preset').value = config.apiPreset || 'custom';
    form.querySelector('#api-key').value = config.apiKey || '';
    form.querySelector('#api-url').value = config.baseUrl || '';
    
    const modelSelect = form.querySelector('#model');
    if (modelSelect && config.model) {
        const option = modelSelect.querySelector(`option[value="${config.model}"]`);
        if (option) {
            modelSelect.value = config.model;
        }
    }
}

// 显示设置提示
function showSettingsToast(message, type = 'success') {
    // 如果DataService存在，使用其showToast方法
    if (window.DataService && window.DataService.showToast) {
        window.DataService.showToast(message, type);
        return;
    }
    
    // 否则创建一个简单的toast
    let toast = document.querySelector('.settings-toast');
    if (!toast) {
        toast = document.createElement('div');
        toast.className = 'settings-toast';
        document.body.appendChild(toast);
    }
    
    toast.textContent = message;
    if (type === 'error') {
        toast.classList.add('error');
    } else {
        toast.classList.remove('error');
    }
    
    toast.classList.add('show');
    
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// 当DOM加载完成后初始化设置
document.addEventListener('DOMContentLoaded', initSettings);

// 导出公共接口
window.SettingsManager = {
    initSettings,
    toggleSettingsPanel,
    closeSettingsPanel,
    saveSettings,
    resetSettings
}; 